# -*- coding: UTF-8 -*-
from django.shortcuts import render
from django.http import HttpResponse

import json
import traceback

from yiqiu_core.ChessBoard import GameCaretaker
from yiqiu_core.Position import ChessPosition

GameManager = GameCaretaker()


class GameType:
    Wuzi = 0
    Go = 1

    def GetType(self, index):
        if index == 0:
            return 'Wuzi'
        elif index == 1:
            return 'Go'
        else:
            raise Exception('!')


def IndexPage(request):
    memento_list = [{'index': i, 'description': description}
                    for i, description in enumerate(GameManager.ShowMementos())]
    print(memento_list)
    return render(request, "index.html", locals())


def CreateGame(request):
    if 'POST' not in request.method:
        return HttpResponse(json.dumps({
            'code': 1,
            'data': None,
            'message': '本接口仅支持 POST 方法'
        }))

    # int 类型, 0 or 1, 对应 'Wuzi' or 'Go', 见 GameType
    game_type = int(request.POST['game_type'])
    print(game_type)
    board_row_num = int(request.POST['row_num'])
    board_col_num = int(request.POST['col_num'])

    # 如果没有指定规则，则使用默认标准规则
    if 'rule_name' not in request.POST.keys():
        rule_name = 'standard_wuzi' if game_type == GameType.Wuzi else 'standard_go'
        print(rule_name)
    else:
        rule_name = request.POST['rule_name']

    success, game_uuid, msg = GameManager.CreateGame(
        board_row_num, board_col_num, rule_name)

    return HttpResponse(json.dumps({
        'code': 0 if success else 1,
        'data': game_uuid,
        'message': msg
    }))


def MakeAMove(request):
    if 'POST' not in request.method:
        return HttpResponse(json.dumps({
            'code': 1,
            'data': None,
            'message': '本接口仅支持 POST 方法'
        }))

    game_uuid = request.POST['game_uuid']
    position_row = int(request.POST['position_row'])
    position_col = int(request.POST['position_col'])

    # 待返回的数据，先初始化一个默认值
    success, data, message = True, None, ""
    if game_uuid not in GameManager.active_games.keys():
        success = False
        message = "当前不存在 uuid 为 %s 的活跃对局" % game_uuid
    else:
        print(position_row, position_col)
        is_legal_move, winner = GameManager.active_games[game_uuid].PlaceChess(
            ChessPosition(position_row, position_col)
        )
        if not is_legal_move:
            success = False
            message = "您不能在此处落子！"
        else:
            data = {
                'board': GameManager.active_games[game_uuid].chess_board.GetBoardStatus().tolist(),
                'has_winner': False if winner is None else True,
                'winner_index': winner  # 0 为平局，1 为黑胜，2 为白胜
            }

    return HttpResponse(json.dumps({
        'code': 0 if success else 1,
        'data': data,
        "message": message
    }))


def MakeARegret(request):
    if 'POST' not in request.method:
        return HttpResponse(json.dumps({
            'code': 1,
            'data': None,
            'message': '本接口仅支持 POST 方法'
        }))

    game_uuid = request.POST['game_uuid']

    # 待返回的数据，先初始化一个默认值
    success, data, message = True, None, ""
    if game_uuid not in GameManager.active_games.keys():
        success = False
        message = "当前不存在 uuid 为 %s 的活跃对局" % game_uuid
    else:
        regret_successfully, hint = GameManager.active_games[game_uuid].Regret(
        )
        if not regret_successfully:
            success = False
            message = "悔棋失败, {}".format(hint)
        else:
            message = "悔棋成功"
            data = {
                'board': GameManager.active_games[game_uuid].chess_board.GetBoardStatus().tolist(),
            }

    return HttpResponse(json.dumps({
        'code': 0 if success else 1,
        'data': data,
        "message": message
    }))


def Save_The_Memento(request):
    if 'POST' not in request.method:
        return HttpResponse(json.dumps({
            'code': 1,
            'data': None,
            'message': '本接口仅支持 POST 方法'
        }))

    game_uuid = request.POST['game_uuid']
    memento_description = request.POST['memento_description']

    # 待返回的数据，先初始化一个默认值
    success, message = True, "创建存档成功"
    try:
        GameManager.CreateMemento(game_uuid, memento_description)
    except Exception:
        success = False
        message = "创建存档失败, {}".format(traceback.format_exc())

    return HttpResponse(json.dumps({
        'code': 0 if success else 1,
        'data': memento_description,
        "message": message
    }))


def Display_Mementos(request):
    return HttpResponse(json.dumps({
        'code': 0,
        'data': GameManager.ShowMementos(),
        'message': ''
    }))


def Load_Memento(request):
    if 'POST' not in request.method:
        return HttpResponse(json.dumps({
            'code': 1,
            'data': None,
            'message': '本接口仅支持 POST 方法'
        }))

    game_uuid = request.POST['game_uuid']
    memento_index = int(request.POST['memento_index'])

    # 待返回的数据，先初始化一个默认值
    success, data, message = True, None, ""
    try:
        GameManager.RestoreMementos(game_uuid, memento_index)
        message = "读档成功"
        game = GameManager.active_games[game_uuid]
        game_board = game.chess_board.GetBoardStatus()
        data = {
            'board': game_board.tolist(),
            'row_num': game_board.shape[0],
            'col_num': game_board.shape[1],
            'current_turn': game._defer_next_chesstype()
        }
    except Exception:
        success = False
        message = "读档失败, {}".format(traceback.format_exc())

    return HttpResponse(json.dumps({
        'code': 0 if success else 1,
        'data': data,
        "message": message
    }))
